var socket;
var keepAliveTimer;

$(function () {
    changeWH();
    loadEnterprise();
     createWebSocket();
    //右上角时间
    if ($('#time_time').length > 0) {
        var nowTime = getFormatTime();
        $('#time_time').text(nowTime.formatTime);
        $('#time_week').text(nowTime.week);
        $('#time_date').text(nowTime.formatDate);
        var timer = setInterval(function () {
            var nowTime = getFormatTime();
            $('#time_time').text(nowTime.formatTime);
            $('#time_week').text(nowTime.week);
            $('#time_date').text(nowTime.formatDate);
        }, 1000);
    }

})

function createWebSocket() {
    if (window.WebSocket) {
        socket = new WebSocket('wss://' + window.location.host + '/ws');
        initWebSocket();
    } else {
        console.log("你的浏览器不支持WebSocket，尝试使用火狐或者谷歌");
    }
}

function initWebSocket() {
    socket.onmessage = function (event) {
        if (event['data'] == enterprise) {
            $('#remind_id').removeClass('alarm-icon-dot');
            $('#remind_id').addClass('alarm-icon-dot');
        }
    };
    socket.onopen = function (event) {

        /*     keepAliveTimer = setInterval(function () {
                 socket.send("keep_alive");
             }, 30000);*/
    };
    socket.onclose = function (event) {
        console.log("连接已关闭");
        clearInterval(keepAliveTimer);
    };
    socket.onerror = function (event) {
        console.log("error")
    }
}

/*根据用户登录信息展示详细企业信息*/
function showEnterpriseData() {
    getJson("/company/getCompanyById", null, 'GET', function (result) {
        $('#photo_img').attr('src', fileUrl + result.photo);
        $('#c_name').text(result.name);
        sessionStorage.setItem("company_name", result.name);
        $('#c_address').text(result.province + result.city + result.address);
        $('#culture').text(result.culture);
        $('#introduction').text(result.introduction);
        if (result.position) {
            var mapObj = new AMap.Map('mapContainer', {
                resizeEnable: true,
                // center: new AMap.LngLat(113.535207, 34.797802),
                zoom: 13
            });
            new AMap.Marker({
                position: result.position.split(","),   //基点位置
                offset: {x: 0, y: 0}, //相对于基点的位置
                map: mapObj,
                anchor: 'center',
                icon: '../customize/images/icon/gis-icon.png'
            });
            mapObj.setCenter(result.position.split(","));
        }
        $('#CompanyInfoModal').modal();
    })
}

/* 检测窗口大小改变 */
var resizeWaiter = false;
$(window).resize(function () {
    if (!resizeWaiter) {
        resizeWaiter = true;
        setTimeout(function () {
            changeWH();
            resizeWaiter = false;
        }, 500);
    }
});

function changeWH() {
    var win_w = $(window).outerWidth();
    var scale = win_w / 1920;
    $('body').css({
        height: $(window).outerHeight() / scale
    });
    $('.scroll-body').css({
        transform: 'scale(' + scale + ')'
    });
}

function changeIframeH() {
    var event = document.getElementById('main_iframe');
    $(event).height(0);
    var child_h = event.contentWindow.document.body.scrollHeight + 10;
    var min_h = $(window).outerHeight() - 100;
    $(event).height(child_h);
    if(child_h < min_h){
        $(event).height(min_h);
    }
}

var mainIframeUrlCookie = 'index.html';
if ($.cookie('mainIframeUrlCookie')) {
    mainIframeUrlCookie = $.cookie('mainIframeUrlCookie');
} else {
    $.cookie('mainIframeUrlCookie', 'index.html', {path: '/'});
}
$("#main_iframe").prop("src", mainIframeUrlCookie);

function logout() {
    getJson('/sys/logout', {token:sessionStorage.getItem("token")}, 'GET', function (data) {
        myAlert('提示', data['message'], function () {
            top.location.href = host + '/index.html';
        });
    })
}

function toSubPage(url) {
    $("#main_iframe").prop("src", url);
    $.cookie('mainIframeUrlCookie', url, {path: '/'});
}

function toSubPageActive(e, url) {
    $(e).addClass('active').siblings().removeClass('active');
    $("#main_iframe").prop("src", url);
}

var fullscreenStatus = false; //全屏状态，默认非全屏
/* 全屏 */
function handleFullScreen(e) {
    var element = document.documentElement;
    if (fullscreenStatus) {//当前全屏
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        fullscreenStatus = false;
        $(e).children().removeClass('icon-suoxiaoicon1').addClass('icon-fangdaicon1');
    } else {
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
            // IE11
            element.msRequestFullscreen();
        }
        fullscreenStatus = true;
        $(e).children().addClass('icon-suoxiaoicon1').removeClass('icon-fangdaicon1');
    }
}

/*消息提醒弹窗*/
function showMessageModal() {
    $('#alarm_type').val(0);
    recentNotice();
    $('#remind_id').removeClass('alarm-icon-dot');
    $('#MessageModal').modal();
}

/*切换消息提醒两个块展示*/
function switchMessageSec(e, index) {
    $('#method_type').val(index);
    $(e).addClass('active').parent().siblings('.nav-item').children().removeClass('active');
    recentNotice();
}

/*近期通知*/
function recentNotice(_pageIndex) {
    showLoading(LOADING);
    var pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    getJson("/alarm/recentAlertNotification", {
        type: $('#alarm_type').val(),
        methodType: $('#method_type').val(),
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (result) {
        buildDiv(result['payload']['data'], $('#recentNotice_div'), $('#method_type').val());
        setPageSimple($('#message_page'), pageIndex, result['payload']['pages'], result['payload']['total'], function (num) {
            recentNotice(num);
        });
        hideLoading();
    })

}

function buildDiv(data, div, method) {
    $(div).empty();
    if (data && data.length > 0) {
        data.map(function (item) {
            var parentDiv = createElement('div', div, null, null);
            $(parentDiv).addClass('bg-paragragh py-1 px-3 mb-2');
            var div1;
            var svg;
            if (item['grade'] > 0) {
                var grade = '';
                switch (item['grade']) {
                    case 1:
                        grade = '[普通]';
                        break;
                    case 2:
                        grade = '[一般]';
                        break;
                    case 3:
                        grade = '[严重]';
                        break;
                    case 4:
                        grade = '[故障]';
                        break;
                }
                if (method == 0) {
                    div1 = createElement('div', parentDiv, item['name'] + '因' + item['content'] + '原因发生了  ' + grade + '  等级告警，请及时关注！', null)
                } else {
                    div1 = createElement('div', parentDiv, item['name'] + '因' + item['content'] + '原因发生了  ' + grade + '  等级告警，已超过五日未解决。请及时关注！', null)
                }
                svg = '<svg class="message-type"><use xlink:href=\'#icon-gaojingtongzhi\'></use></svg>';
            } else {
                var days = Math.abs(item['result']);
                if (method == 0) {
                    if (days == 0) {
                        div1 = createElement('div', parentDiv, item['name'] + '设备维保期限将至，请及时关注！', null)
                    } else if (days > 0 && days < 5) {
                        div1 = createElement('div', parentDiv, item['name'] + '设备原定维保日期' + item['content'] + '已超出维保期限' + days + '天，请及时关注！', null)
                    }
                } else {
                    div1 = createElement('div', parentDiv, item['name'] + '设备原定维保日期' + item['content'] + '已超出维保期限' + days + '天，请及时关注！', null)
                }
                svg = '<svg class="message-type"><use xlink:href=\'#icon-weibaotongzhi\'></use></svg>';
            }
            $(div1).addClass('font-p14 mb-1');
            var div2 = createElement('div', parentDiv, null, null);
            $(div2).addClass('d-flex justify-content-between align-items-center');
            $(div2).append(svg);
            var div3 = createElement('div', div2, item['createtime'], null);
            $(div3).addClass('font-p12 text-blue-a');
        });
    }
}

function toManagement() {
    myConfirm('后台管理', '点击后将转至后台管理系统，是否确认打开？', function (res) {
        if (res) {
            var token = sessionStorage.getItem("token");
            window.open(gldUrl + "?token=" + token);
        }
    })
}
